class RobotStateManager {
    constructor() {
        // 定义默认状态结构
        this.state = {
            components: {},  // 添加 components 顶级节点
            robot: {}
        };

        // 机器人初始状态
        this.state.robot = {
            status: 'idle',      // 工作状态: idle, working, charging, error
            mode: 'normal',      // 工作模式: normal, strong, quiet, custom
            battery: 0.2,        // 电量: 0-1
            error: null,          // 错误信息
            waterLevel: 1,
            fanLevel: 1,
            lineSpeed: 100,
            angularSpeed: 100,
            angularSpeed: 40,
            leftWheelRpm: 10,
            leftWheelRpm: 10,
            leftEncoderpulse: 10,
            rightEncoderpulse: 10,
            allEncoderpulse: 100,
            mission: {
            }
        }

        this.state.robot.mission = {
            status: 'idle',           // 任务状态: idle, running, paused, docking, spot, error
            currentMode: 'standard',  // 清扫模式: standard, strong, quiet, custom
            cleanArea: 0,            // 清扫面积(平方米)
            cleanTime: 0,            // 清扫时间(秒)
            batteryStart: 0,         // 开始清扫时的电量
            lastError: null,         // 最后一次错误信息
            settings: {
                waterLevel: 1,       // 出水量: 1-3
                suctionPower: 1,     // 吸力: 1-3
                cleanTimes: 1        // 清扫次数: 1-2
            },
            statistics: {
                totalArea: 0,        // 总清扫面积
                totalTime: 0,        // 总清扫时间
                totalCount: 0        // 总清扫次数
            }
        };

        // 组件初始状态
        this.state.components = {
            // 运动系统状态
            motion: {
                linearSpeed: 0,      // 线速度(mm/s)
                angularSpeed: 0,     // 角速度(mrad/s)
                moveDirection: null, // 当前运动方向
                wheels: {
                    left: {
                        rotating: false,
                        speed: 0,
                        offGround: false
                    },
                    right: {
                        rotating: false,
                        speed: 0,
                        offGround: false
                    }
                }
            },

            // 清扫系统状态
            cleaning: {
                vacuum: {
                    enabled: false,
                    fanSpeed: 0    // 吸力等级 0-100
                },
                brush: {
                    side: {
                        enabled: false,
                        speed: 0
                    },
                    main: {
                        enabled: false,
                        speed: 0
                    }
                },
                mop: {
                    lift: false,
                    vibrate: false,
                    waterFlow: 0
                }
            },

            // 传感器系统状态
            sensors: {
                camera: {
                    main: {
                        enabled: false,
                        fps: 30,
                        fillLight: false
                    }
                },
                lidar: {
                    rotating: false,
                    speed: 0,
                    switches: {
                        front: false,
                        back: false,
                        left: false,
                        right: false
                    }
                },
                frontBumper: {
                    left: false,   // 左前碰撞
                    right: false   // 右前碰撞
                },
                cliff: {
                    left: false,
                    frontLeft: false,
                    frontRight: false,
                    right: false
                },
                ir: {
                    left: false,
                    leftMid: false,
                    leftRear: false,
                    rightRear: false,
                    rightMid: false,
                    right: false
                },
                lineLaser: {
                    enabled: false
                },
                tof: {
                    enabled: false
                }
            },

            // 容器状态
            containers: {
                waterTank: {
                    attached: false,
                    level: 0        // 水位 0-100
                },
                dustbin: {
                    attached: false,
                    full: false
                },
                cleaningFluid: {
                    attached: false,
                    level: 0,       // 清洁液液位 0-100
                    type: 'none'    // 清洁液类型: 'none', 'standard', 'strong', 'eco'
                }
            },
            keyLeds: {
                powerButton: {
                    ledOn: false,
                    pressed: false
                },
                homeButton: {
                    ledOn: false,
                    pressed: false
                }
            }
        };

        this.listeners = new Set();
        this.componentListeners = new Set();

        // 初始化完成后触发一次状态更新
        setTimeout(() => {
            this.notifyListeners({
                type: 'init',
                state: this.state
            });
        }, 0);
    }

    // 获取完整状态
    getState() {
        return this.state;
    }

    // 获取任意路径的状态值
    getStateValue(path) {
        if (!path) {
            console.warn('No path provided to getStateValue');
            return null;
        }

        try {
            const normalizedPath = this.normalizePath(path);
            return normalizedPath.split('.').reduce((obj, key) =>
                obj && obj[key] !== undefined ? obj[key] : null, this.state);
        } catch (error) {
            console.warn(`Error getting state value for path: ${path}`, error);
            return null;
        }
    }

    // 更新组件状态
    updateComponentState(path, value, silent = false) {
        try {
            const normalizedPath = this.normalizePath(path);
            const pathArray = normalizedPath.split('.');
            const lastKey = pathArray.pop();

            const target = pathArray.reduce((obj, key) => {
                if (!(key in obj)) {
                    obj[key] = {};
                }
                return obj[key];
            }, this.state);

            if (target[lastKey] !== value) {
                const oldValue = target[lastKey];
                target[lastKey] = value;

                if (!silent) {
                    const event = {
                        path: normalizedPath,
                        oldValue,
                        newValue: value,
                        timestamp: Date.now()
                    };

                    // 分别处理普通监听器和组件监听器
                    this.notifyListeners(event);
                    //this.notifyComponentListeners(this.state.components);
                }
            }

            return true;
        } catch (error) {
            console.error(`Error updating state at path ${path}:`, error);
            return false;
        }
    }

    // 添加任务状态更新方法
    updateMissionState(action, params = {}) {
        console.log('Updating mission state:', action, params);

        switch(action) {
            case 'start':
                this.state.robot.mission.status = 'running';
                this.state.robot.mission.currentMode = params.mode || 'standard';
                this.state.robot.mission.batteryStart = this.state.robot.battery;
                break;

            case 'pause':
                this.state.robot.mission.status = 'paused';
                break;

            case 'resume':
                this.state.robot.mission.status = 'running';
                break;

            case 'dock':
                this.state.robot.mission.status = 'docking';
                break;

            case 'spot':
                this.state.robot.mission.status = 'spot';
                break;

            case 'complete':
                this.state.robot.mission.status = 'idle';
                // 更新统计信息
                this.state.robot.mission.statistics.totalArea += this.state.robot.mission.cleanArea;
                this.state.robot.mission.statistics.totalTime += this.state.robot.mission.cleanTime;
                this.state.robot.mission.statistics.totalCount++;
                break;

            case 'error':
                this.state.robot.mission.status = 'error';
                this.state.robot.mission.lastError = params.error;
                break;

            case 'updateSettings':
                if (params.waterLevel !== undefined) {
                    this.state.robot.mission.settings.waterLevel = params.waterLevel;
                }
                if (params.suctionPower !== undefined) {
                    this.state.robot.mission.settings.suctionPower = params.suctionPower;
                }
                if (params.cleanTimes !== undefined) {
                    this.state.robot.mission.settings.cleanTimes = params.cleanTimes;
                }
                break;
        }

        // 通知监听器状态已更新
        this.notifyListeners({
            type: 'missionUpdate',
            action: action,
            params: params,
            timestamp: Date.now()
        });
    }

    // 路径标准化
    normalizePath(path) {
        if (path.startsWith('components.')) {
            return path;
        }

        if (path.startsWith('robot.')) {
            return path;
        }

        if (path.match(/^(motion|cleaning|sensors|containers|keyLeds)\./)) {
            return `components.${path}`;
        }

        return path;
    }

    // 添加普通状态监听器
    addListener(callback) {
        if (typeof callback === 'function') {
            this.listeners.add(callback);
        }
    }

    // 添加组件状态监听器
    addComponentListener(callback) {
        if (typeof callback === 'function') {
            this.componentListeners.add(callback);
        }
    }

    // 移除监听器
    removeListener(callback) {
        this.listeners.delete(callback);
        this.componentListeners.delete(callback);
    }

    // 添加专门的组件监听器
    addComponentListener(callback) {
        if (typeof callback === 'function') {
            this.componentListeners.add(callback);
        }
    }

    notifyListeners(event) {
        if (this.isUpdating) return;
        this.isUpdating = true;

        try {
            const state = this.getState();
            // 先通知普通监听器
            this.listeners.forEach(listener => {
                try {
                    listener(state, event);
                } catch (error) {
                    if (!(error instanceof ReferenceError && error.message.includes('robotComponentManager'))) {
                        console.error('Error in state listener:', error);
                    }
                }
            });

            // 如果存在组件管理器，再通知组件监听器
            if (window.componentManager) {
                this.componentListeners.forEach(listener => {
                    try {
                        listener(state.components);
                    } catch (error) {
                        console.error('Error in component listener:', error);
                    }
                });
            }
        } finally {
            this.isUpdating = false;
        }
    }

    // 通知组件监听器
    notifyComponentListeners(components) {
        this.componentListeners.forEach(listener => {
            try {
                listener(components);
            } catch (error) {
                // 忽略组件管理器未定义的错误
                if (!(error instanceof ReferenceError && error.message.includes('robotComponentManager'))) {
                    console.warn('Error in component listener:', error);
                }
            }
        });
    }

    // 销毁实例
    destroy() {
        this.listeners.clear();
        this.componentListeners.clear();
    }

    // Method to handle component updates
    updateComponent(path, value) {
        // Convert component path to state path
        const statePath = this.normalizeComponentPath(path);
        return this.updateComponentState(statePath, value);
    }

    normalizeComponentPath(path) {
        // Ensure component paths are properly formatted
        if (!path.startsWith('components.')) {
            return `components.${path}`;
        }
        return path;
    }
}

// 创建全局单例
const robotStateManager = new RobotStateManager();

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.robotStateManager = robotStateManager;
    window.RobotStateManager = RobotStateManager;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        RobotStateManager,
        robotStateManager
    };
}
